import json
import logging
from datetime import datetime
from typing import Any

from django.conf import settings
from django.core.cache import caches

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class HybridCache:
    def __init__(self):
        self.redis = caches['default']
        self.local = caches['local']

    def _ensure_connection(self):
        """检查Redis连接状态"""
        try:
            self.redis.client.get_client().ping()
            self.redis_available = True
        except Exception as e:
            self.redis_available = False
            logger.error(f"Redis连接检查失败: {str(e)}")

    def get(self, key: str) -> Any | None:
        """获取缓存数据"""
        try:
            # 优先尝试Redis
            if self.redis_available:
                if (value := self.redis.get(key)) is not None:
                    logger.info(f"💾 [Redis] 缓存命中: {key}")
                    return json.loads(value)
        except Exception as e:
            logger.error(f"📦 [Redis] 获取失败: {str(e)}")
            self.redis_available = False

        # 回退到本地缓存
        if (value := self.local.get(key)) is not None:
            logger.info(f"💾 [Local] 缓存命中: {key}")
            return value

        logger.info(f"⏳ 缓存未命中: {key}")
        return

    def set(self, key: str, value: dict, ttl: int = None) -> bool:
        """设置缓存数据"""
        ttl = ttl or settings.CACHE_TTL
        success = True

        try:
            # 序列化并存储到Redis
            serialized = json.dumps(value, default=self._json_serial)
            self.redis.set(key, serialized, timeout=ttl)
            logger.info(f"💾 [Redis] 缓存设置: {key} (TTL: {ttl}s)")
        except Exception as e:
            success = False
            logger.error(f"📦 [Redis] 设置失败: {str(e)}")
            self.redis_available = False

        # 总是写入本地缓存
        self.local.set(key, value, timeout=ttl)
        logger.info(f"💾 [Local] 缓存设置: {key} (TTL: {ttl}s)")

        return success

    def delete(self, key: str) -> bool:
        """删除缓存数据"""
        redis_success = True
        try:
            self.redis.delete(key)
            logger.info(f"🗑️ [Redis] 缓存删除: {key}")
        except Exception as e:
            redis_success = False
            logger.error(f"📦 [Redis] 删除失败: {str(e)}")
            self.redis_available = False

        local_success = self.local.delete(key) > 0
        logger.info(f"🗑️ [Local] 缓存删除: {key}")

        return redis_success and local_success

    def _json_serial(self, obj):
        """JSON序列化处理器"""
        if isinstance(obj, datetime):
            return obj.isoformat()
        raise TypeError(f"无法序列化类型 {type(obj)}")